module source.modules;

import  std.process : escapeShellCommand, spawnShell, Config;
import     std.json : JSONValue;
import    std.array : split;
import     std.conv : to;

import source.config : ConfigManager;
import source.logger : LoggerWriter;

class ModuleManager
{
    private string modulespath;
    private string configpath;
    private ConfigManager configuration;
    private LoggerWriter logger;
    private int tfKey;

    private string[] activeModules;

    this(string modulepath, string configpath, ConfigManager manager, LoggerWriter logger, int tempfileK)
    {
        this.modulespath = modulepath;
        this.configpath = configpath;
        this.configuration = manager;
        this.logger = logger;
        this.tfKey = tempfileK;
    }

    public void runModules(string ircText)
    {
        JSONValue sets = [
            "prefix": this.configuration.prefix,
            "opPrefix": this.configuration.opPrefix
        ];
        sets.object["apis"] = JSONValue(this.configuration.apiKeys);
        sets.object["access"] = JSONValue(this.configuration.accessibility);

        for (int i = 0; i < this.activeModules.length; i++)
        {
            char[] toRun = this.modulespath.dup ~ "/" ~ this.activeModules[i] ~ " " ~
                "Norbit." ~ to!string(this.tfKey) ~ " " ~
                escapeShellCommand(ircText) ~ " " ~
                escapeShellCommand(sets.toString);
            spawnShell(toRun, cast(const(string[string]))null, Config.detached);  // programname persist.1234 'PRIVMSG blah' '{"settings"}'
        }
    }

    public void reloadModules()
    {
        this.activeModules = this.activeModules.init;
        for (int i = 0; i < this.configuration.available.length; i++)
        {
            this.activeModules ~= this.configuration.available[i];
        }
    }
}
